package main

import (
	"fmt"
	"html/template"
	"math/rand"
	"net/http"

	"github.com/gin-gonic/gin"
)

type phoneData struct {
	Manufacture string
	Selldata    []float32
	Q3comp      float32
}

type filterRequest struct {
	ManufactureID int    `form:"manufacture"`
	Title         string `form:"title"`
}

func formatAsPercentage(data float32) string {
	return fmt.Sprintf("%.2f", data*100) + " %"
}

func sumAllSeason(data []float32) string {
	var ret float32 = 0
	for _, i := range data {
		ret += i
	}
	return fmt.Sprintf("%.2f", ret)
}

func toFixed2(data float32) string {
	return fmt.Sprintf("%.2f", data)
}

func getData() []phoneData {
	return []phoneData{
		phoneData{
			Manufacture: "华为",
			Selldata:    []float32{rand.Float32() * 20, rand.Float32() * 20, rand.Float32() * 20},
			Q3comp:      (rand.Float32() - 0.5) * 0.2,
		},
		phoneData{
			Manufacture: "OPPO",
			Selldata:    []float32{rand.Float32() * 10, rand.Float32() * 10, rand.Float32() * 10},
			Q3comp:      (rand.Float32() - 0.5) * 0.2,
		},
		phoneData{
			Manufacture: "小米",
			Selldata:    []float32{rand.Float32() * 15, rand.Float32() * 15, rand.Float32() * 15},
			Q3comp:      (rand.Float32() - 0.5) * 0.2,
		},
		phoneData{
			Manufacture: "OV",
			Selldata:    []float32{rand.Float32() * 10, rand.Float32() * 10, rand.Float32() * 10},
			Q3comp:      (rand.Float32() - 0.5) * 0.2,
		},
		phoneData{
			Manufacture: "Apple",
			Selldata:    []float32{rand.Float32() * 12, rand.Float32() * 12, rand.Float32() * 12},
			Q3comp:      (rand.Float32() - 0.5) * 0.2,
		},
	}
}

func main() {
	r := gin.Default()
	r.Static("/static", "./static")
	r.SetFuncMap(template.FuncMap{
		"formatAsPercentage": formatAsPercentage,
		"sumAllSeason":       sumAllSeason,
		"toFixed2":           toFixed2,
	})
	r.LoadHTMLGlob("./templates/*")
	r.GET("/api/data", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"data": getData(),
		})
	})

	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.tmpl", gin.H{
			"title": "手机销量",
			"data":  getData(),
		})
	})

	r.POST("/", func(c *gin.Context) {
		data := getData()
		var req filterRequest
		var ret *[]phoneData
		c.Bind(&req)
		if req.ManufactureID < len(data) && req.ManufactureID >= 0 {
			ret = &[]phoneData{data[req.ManufactureID]}
		} else {
			ret = &data
		}
		c.HTML(http.StatusOK, "index.tmpl", gin.H{
			"title": req.Title,
			"data":  *ret,
		})
	})

	r.Run(":8080")
}
